package com.diaoyanbao.module;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.TreeMap;

import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.diaoyanbao.model.CSSFileVersionADT;
import com.diaoyanbao.model.FileVersionADT;
import com.diaoyanbao.service.BaseService;

/**
 * css 模块
 * 
 * @author dingxs
 */
public class CSSModule extends BaseModule {
    private FileVersionADT fileVersionADT;
    private Map<String, String> fileMap;
    private String regex;

    public CSSModule() {
        fileVersionADT = new CSSFileVersionADT();
        fileVersionADT.initFileVersionInfo(BaseService.configProp.getProperty("CSS_DIR"));
        fileMap = fileVersionADT.getFileVersionInfo();
        regex = BaseService.configProp.getProperty("CSS_REGEX_PREFIX");
    }

    public Map<String, String> getFileMap() {
        return fileMap;
    }

    /**
     * 更新jsp
     * 
     * @param filePath
     * @param regex
     * @throws ParserException,IOException
     */
    public void updateJspRef(String filePath) throws ParserException, IOException {
        TreeMap<String, String> map = (TreeMap<String, String>) BaseService.fileInfo.get("css");
        Parser parser = new Parser(filePath);
        parser.setEncoding("UTF-8");
        NodeList nodeList = parser.parse(null);
        for (int i = 0; i < nodeList.size(); i++) {
            Node node = nodeList.elementAt(i);
            if (node instanceof Tag && ((Tag) node).getTagName().equals("LINK") && ((Tag) node).getAttribute("href") != null) {
                Tag tag = (Tag) node;
                String hrefValue = tag.getAttribute("href");
                //文件配置key为文件路径去除公共部分和后缀
                String configKey = hrefValue.replaceFirst(regex, "");
                configKey = configKey.substring(0, configKey.lastIndexOf("."));
                if (map.get(configKey) != null) {
                    if (hrefValue.contains("?")) {
                        hrefValue = hrefValue.replaceFirst("(\\?v=)(\\w)+", "?v=".concat(map.get(configKey)));
                    } else {
                        hrefValue = hrefValue + "?v=" + map.get(configKey);
                    }
                }
                logger.info(hrefValue);
                tag.setAttribute("href", hrefValue);
            }
        }
        File jspFile = new File(filePath);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(jspFile)));
        writer.write(nodeList.toHtml(), 0, nodeList.toHtml().length());
        writer.flush();
        writer.close();
    }
}
